import { Injectable } from '@angular/core';

import { ConfService } from '../conf.service';
import { GitProxyService } from '../git-proxy.service';
import { UtilsService } from '../utils.service';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class BlogService {

  constructor(
    private confService: ConfService,
    private gitProxyService: GitProxyService,
    private utilsService: UtilsService
  ) { }

  getDirContents(path='/docs'): Promise<any[]> {
    return this.gitProxyService
      .getDirContents(
        this.confService.config.owner,
        this.confService.config.repo,
        path,
        this.confService.config.branch)
      .catch(error => {
        return Observable.of<any[]>([]).toPromise();
      });
  }

  getFileContent(path: string): Promise<any> {
    return this.gitProxyService
      .getFileContent(
        this.confService.config.owner,
        this.confService.config.repo,
        path,
        this.confService.config.branch);
  }

  // 创建博文
  createFile(dir: string, file: string): Promise<any> {
    return this.gitProxyService
      .createFile(
        this.confService.config.owner,
        this.confService.config.repo,
        '/' + 'docs/' + dir + '/' + file + '.md',
        this.utilsService.b64EncodeUnicode('# ' + file),
        ':memo: 创建了《' + file + '》',
        sessionStorage.getItem('access_token'),
        this.confService.config.branch
      )
  }

  deleleFile(fileContents: any): Promise<any> {
    return this.gitProxyService
      .deleteFile(
        this.confService.config.owner,
        this.confService.config.repo,
        '/' + fileContents.path,
        fileContents.sha,
        ':memo: 删除了《' + fileContents.name + '》',
        sessionStorage.getItem('access_token'),
        this.confService.config.branch
      );
  }

  // 更改博文
  updateFile(fileContents: any, content: string): Promise<any> {
    return this.gitProxyService
      .updateFile(
        this.confService.config.owner,
        this.confService.config.repo,
        '/' + fileContents.path,
        this.utilsService.b64EncodeUnicode(content),
        fileContents.sha,
        ':memo: 更新了《' + fileContents.name + '》',
        sessionStorage.getItem('access_token'),
        this.confService.config.branch
      );
  }
}
